package com.sys.SysSales.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.sys.common.utils.DateUtils;
import com.sys.common.utils.OrderNumberUtils;
import com.sys.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.sys.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.sys.SysSales.domain.SysSalesOrderDetails;
import com.sys.SysSales.mapper.SysSalesOrdersMapper;
import com.sys.SysSales.domain.SysSalesOrders;
import com.sys.SysSales.service.ISysSalesOrdersService;

/**
 * 订单主表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-26
 */
@Service
public class SysSalesOrdersServiceImpl implements ISysSalesOrdersService 
{
    @Autowired
    private SysSalesOrdersMapper sysSalesOrdersMapper;

    /**
     * 查询订单主表
     * 
     * @param orderId 订单主表主键
     * @return 订单主表
     */
    @Override
    public SysSalesOrders selectSysSalesOrdersByOrderId(Long orderId)
    {
        return sysSalesOrdersMapper.selectSysSalesOrdersByOrderId(orderId);
    }

    /**
     * 查询订单主表列表
     * 
     * @param sysSalesOrders 订单主表
     * @return 订单主表
     */
    @Override
    public List<SysSalesOrders> selectSysSalesOrdersList(SysSalesOrders sysSalesOrders)
    {
        return sysSalesOrdersMapper.selectSysSalesOrdersList(sysSalesOrders);
    }

    /**
     * 新增订单主表
     * 
     * @param sysSalesOrders 订单主表
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSysSalesOrders(SysSalesOrders sysSalesOrders)
    {

        // 生成20位订单编号并设置到订单对象中
        String orderNo = OrderNumberUtils.generate20BitOrderNo();
        sysSalesOrders.setOrderNumber(orderNo);

        // 如果需要，这里可以添加订单其他默认值设置
        // 例如：设置订单状态为"待付款"、创建时间等
        if (sysSalesOrders.getStatus() == null) {
            sysSalesOrders.setStatus("pending"); // 假设0表示待付款状态
        }

        sysSalesOrders.setCreatedBy(SecurityUtils.getUserId());
        sysSalesOrders.setCreateTime(DateUtils.getNowDate());

        int rows = sysSalesOrdersMapper.insertSysSalesOrders(sysSalesOrders);
        saveOrUpdateOrderDetails(sysSalesOrders);
        return rows;
    }

    /**
     * 修改订单主表
     * 
     * @param sysSalesOrders 订单主表
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSysSalesOrders(SysSalesOrders sysSalesOrders)
    {
        /*如果状态是已发货，就添加实习发货时间*/
        if ("shipped".equals(sysSalesOrders.getStatus())) {
            sysSalesOrders.setActualDeliveryDate(DateUtils.getNowDate());
        }
        /*如果状态是取消，就添加取消人*/
        if ("shipped".equals(sysSalesOrders.getStatus())) {
            sysSalesOrders.setCanceledBy(SecurityUtils.getUserId());
        }

        sysSalesOrdersMapper.deleteSysSalesOrderDetailsByOrderId(sysSalesOrders.getOrderId());
        saveOrUpdateOrderDetails(sysSalesOrders);
        return sysSalesOrdersMapper.updateSysSalesOrders(sysSalesOrders);
    }

    /**
     * 批量删除订单主表
     * 
     * @param orderIds 需要删除的订单主表主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSysSalesOrdersByOrderIds(Long[] orderIds)
    {
        sysSalesOrdersMapper.deleteSysSalesOrderDetailsByOrderIds(orderIds);
        return sysSalesOrdersMapper.deleteSysSalesOrdersByOrderIds(orderIds);
    }

    /**
     * 删除订单主表信息
     * 
     * @param orderId 订单主表主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSysSalesOrdersByOrderId(Long orderId)
    {
        sysSalesOrdersMapper.deleteSysSalesOrderDetailsByOrderId(orderId);
        return sysSalesOrdersMapper.deleteSysSalesOrdersByOrderId(orderId);
    }

    /**
     * 新增订单明细表信息
     * 
     * @param sysSalesOrders 订单主表对象
     */
    /**
     * 插入或更新订单明细（同时计算总金额）
     * 支持新增和修改场景
     */
    public void saveOrUpdateOrderDetails(SysSalesOrders sysSalesOrders) {
        List<SysSalesOrderDetails> detailsList = sysSalesOrders.getSysSalesOrderDetailsList();
        Long orderId = sysSalesOrders.getOrderId();

        if (StringUtils.isNotNull(detailsList)) {
            // 1. 无论新增还是修改，都基于当前明细重新计算总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            List<SysSalesOrderDetails> list = new ArrayList<>();

            for (SysSalesOrderDetails detail : detailsList) {
                detail.setOrderId(orderId);

                // 计算当前明细的小计（仅用于总金额计算）
                BigDecimal subtotal = new BigDecimal(detail.getQuantity())
                        .multiply(detail.getUnitPrice())
                        .setScale(2, BigDecimal.ROUND_HALF_UP);

                totalAmount = totalAmount.add(subtotal); // 累加当前明细的小计
                list.add(detail);
            }

            // 2. 先删除原有明细（修改时需要清除旧数据）
            sysSalesOrdersMapper.deleteSysSalesOrderDetailsByOrderId(orderId);

            // 3. 插入新的明细列表
            if (!list.isEmpty()) {
                sysSalesOrdersMapper.batchSysSalesOrderDetails(list);
            }

            // 4. 用全新计算的总金额更新订单主表
            sysSalesOrders.setTotalAmount(totalAmount);
            sysSalesOrdersMapper.updateSysSalesOrders(sysSalesOrders);
        }
    }
//    public void insertSysSalesOrderDetails(SysSalesOrders sysSalesOrders)
//    {
//        List<SysSalesOrderDetails> sysSalesOrderDetailsList = sysSalesOrders.getSysSalesOrderDetailsList();
//        Long orderId = sysSalesOrders.getOrderId();
//        if (StringUtils.isNotNull(sysSalesOrderDetailsList))
//        {
//            List<SysSalesOrderDetails> list = new ArrayList<SysSalesOrderDetails>();
//
//            // 初始化总金额，避免null
//            BigDecimal totalAmount = sysSalesOrders.getTotalAmount() != null ?
//                    sysSalesOrders.getTotalAmount() : BigDecimal.ZERO;
//
//            for (SysSalesOrderDetails sysSalesOrderDetails : sysSalesOrderDetailsList)
//            {
//                sysSalesOrderDetails.setOrderId(orderId);
//
//                // 计算当前明细的小计（仅用于累加，不设置到虚拟列）
//                BigDecimal subtotal = new BigDecimal(sysSalesOrderDetails.getQuantity())
//                        .multiply(sysSalesOrderDetails.getUnitPrice())
//                        .setScale(2, BigDecimal.ROUND_HALF_UP);
//
//                // 累加总金额
//                totalAmount = totalAmount.add(subtotal);
//
//
//                list.add(sysSalesOrderDetails);
//
//            }
//            if (list.size() > 0)
//            {
//                sysSalesOrdersMapper.batchSysSalesOrderDetails(list);
//            }
//        }
//    }
}
